package com.chester.springbootseventeen.config.rabbit;

import com.alibaba.fastjson.JSON;
import com.chester.springbootseventeen.entity.Book;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author chester7cheng
 */
@Component
@Slf4j
public class Consumer {
    @RabbitListener(queues = RabbitConfig.DEFAULT_QUEUE)
    public void listenerAutoAck(Channel channel, Message message, Book book){
        log.trace("listenerAutoAck: \n{}\n{}\n{}", JSON.toJSONString(channel), JSON.toJSONString(message), JSON.toJSONString(book));

        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            try {
                channel.basicRecover();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }


    @RabbitListener(queues = {
            RabbitConfig.TOPIC_QUEUE,
            RabbitConfig.FANOUT_QUEUE,
            RabbitConfig.HEADERS_QUEUE})
    public void commonListenerManualAck(Channel channel, Message message, Book book){
        log.trace("commonListenerManualAck: \n{}", JSON.toJSONString(book));

        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();

        }
    }

    @RabbitListener(queues = {RabbitConfig.DEAD_LETTER_QUEUE})
    public void deadLetterListenerManualAck(Channel channel, Message message, String payload){
        log.trace("deadLetterListenerManualAck: \n{}", payload);

        long start = System.currentTimeMillis()/1000;
        try {
            while (true){
                if((System.currentTimeMillis()/1000 - start) > 3){
                    break;
                }
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();

        }
    }
}
